
import requests
from core.config import settings
from core.logger import log
import xml.etree.ElementTree as ET

class WeChatPadClient:
    def __init__(self):
        """
        初始化客户端
        """
        self.session = requests.Session()
        self.base_url = settings.BASE_URL
        self.key = None

    def set_header(self, key: str, value: str):
        """
        设置请求头
        """
        self.session.headers[key] = value

    def get_user_status(self, key: str, **kwargs):
        """
        获取登录状态
        """
        status_url = self.base_url + "/login/GetLoginStatus?key=" + key
        return self.session.get(status_url, params={}, **kwargs)

    def post_login_qr_code(self,key: str, **kwargs):
        """
        获取登录二维码
        """
        qr_code_url = self.base_url + "/login/GetLoginQrCodeNew?key=" + key
        data = {
            "Check": False,
            "Proxy": ""
        }
        return self.session.post(qr_code_url,json=data, **kwargs)

    async def get_lable_list(self,key):
        """
        获取标签列表
        """
        url = f"{settings.BASE_URL}/label/GetContactLabelList?key={key}"
        res = requests.get(url).json()

        if res["Code"] == 200:
            return res["Data"]["labelPairList"]
        else:
            return []
    def get_targe_wx_id(self, key, label_data):
        """
        获取标签列表
        """
        list_label = []
        list_label.append(label_data["labelName"])
        label_data = {
            "LabelId": f"{label_data["labelId"]}",
            "LabelNameList": list_label
        }
        # log.info(f"标签数据：{lable_data}")
        url = f"{settings.BASE_URL}/label/GetWXFriendListByLabel?key={key}"
        res = requests.post(url, json=label_data).json()
        # log.info(f"标签下所有好友：{res}")
        if res["Code"] == 200:
            return res["Data"]
        else:
            return []
    def check_login_status(self, auth_key: str, **kwargs):
        """
        检查登录状态  GET方式
        """
        try:
            check_login_url = settings.BASE_URL + "/login/CheckLoginStatus?key=" + auth_key
            return self.session.get(check_login_url, params={}, **kwargs)
        except Exception as e:
            print(f"检查登录状态失败: {e}")

    def get_all_devices(self, **kwargs):
        """
        获取所有设备
        """
        try:
            devices_url = settings.BASE_URL + "/admin/GetAllDevices?key=" + settings.BASE_KEY
            ret = self.session.get(devices_url, params={}, **kwargs)
            ret_json =  ret.json()
            devices = ret_json["Data"]["devices"]
            return devices
        except Exception as e:
            print(f"获取设备列表失败: {e}")
            return []
    def get_friends_list(self, auth_key, **kwargs):
        """
        获取所有朋友
        """
        try:
            devices_url = settings.BASE_URL + "/friend/GetFriendList?key=" + auth_key
            ret = self.session.get(devices_url, params={}, **kwargs)
            ret_json =  ret.json()
            frd_list = ret_json["Data"]["friendList"]
            return frd_list
        except Exception as e:
            print(f"获取设备列表失败: {e}")
            return []


    def wake_up_wx(self, auth_key: str):
        """
        唤醒微信
        """
        wake_up_url = settings.BASE_URL + "/login/WakeUpLogin?key=" + auth_key
        data = {
            "Check": False,
            "Proxy": ""
        }
        res = self.session.post(wake_up_url, json=data)
        return res

    def get_unuse_devices(self):
        """
        获取未使用的设备
        """
        devices = self.get_all_devices()
        for device in devices:
            if device["status"] == 0:
                return device
        return None

    def create_device(self):
        """
        创建设备http://192.168.1.85:1238/admin/GenAuthKey1 生成授权码(新设备)
        """
        create_device_url = settings.BASE_URL + "/admin/GenAuthKey1?key=" + settings.BASE_KEY
        data = {
            "Count": 1,
            "Days": 360,
            "Remark": ""
        }
        res = self.session.post(create_device_url,json= data)
        ret_json = res.json()
        if ret_json["Code"] == 200:
            return ret_json["Data"]["authKeys"][0]
        return None

    def get_detail_friend_info(self, key, wx_id):
        """
        获取朋友详情
        备注信息：首先查询数据库中有没有这个信息，没有的话就从接口获取
        """
        data = {"UserNames": [wx_id]}
        url = f"{settings.BASE_URL}/friend/GetContactDetailsList?key={key}"
        res = requests.post(url, json=data).json()
        if res["Code"] == 200:
            return res["Data"]["contactList"][0]
        else:
            return None

    def upload_file_to_cdn(self,path: str, file_name: str,key: str):
        try:
            url = f"{settings.BASE_URL}/message/UploadFileToCDN?key={key}"
            data = {
                "FileName": file_name,
                "FileUrl": path
            }
            response = requests.post(url, json=data)
            if response.json()["Code"] == 200:
                log.info(f"Upload successful: {response.json()}")
                return response.json()
            else:
                log.info(f"Error: {response.json()}")
                return None
        except Exception as e:
            log.info(f"Error occurred: {e}")
            return None

    def build_content_xml(self,upload_response: dict) -> str:
        """
        根据上传接口返回的数据构建 ContentXML
        :param upload_response: UploadFileToCDN 接口返回的 JSON 数据
        :return: XML 字符串
        """
        # 提取必要字段
        AESKey = upload_response.get('AESKey')
        AttachID = upload_response.get('AttachID')
        CDNAntachURL = upload_response.get('CDNAttachURL')
        EncryVer = upload_response.get('EncryVer')
        FileExt = upload_response.get('FileExt')
        FileName = upload_response.get('FileName')
        TotalLen = upload_response.get('TotalLen')
        MD5 = upload_response.get('MD5')

        # 创建根节点
        root = ET.Element('appmsg')
        root.set('appid', '')
        root.set('sdkver', '0')

        # 添加子节点
        ET.SubElement(root, 'title').text = FileName
        ET.SubElement(root, 'type').text = '6'
        ET.SubElement(root, 'md5').text = MD5  # 注意：这里不需要 cdata，因为值是纯文本

        # appattach 节点
        appattach = ET.SubElement(root, 'appattach')
        ET.SubElement(appattach, 'totallen').text = str(TotalLen)
        ET.SubElement(appattach, 'attachid').text = AttachID
        ET.SubElement(appattach, 'fileext').text = FileExt
        ET.SubElement(appattach, 'cdnattachurl').text = CDNAntachURL
        ET.SubElement(appattach, 'aeskey').text = AESKey
        ET.SubElement(appattach, 'encryver').text = EncryVer

        # 转换为字符串
        xml_str = ET.tostring(root, encoding='unicode')
        return xml_str